let login_runing = false;
let login_collect = [];
let login_request_count = 0;

//load提示加载
let Loading = {
  count: 0,
  start: function () {
    wx.showLoading({
      title: "加载中..."
    });
  },
  end: function () {
    wx.hideLoading();
  },
  show: function () {
    if (this.count === 0) {
      this.start();
    };
    this.count++;
  },
  hide: function () {
    if (this.count <= 0) return;
    this.count--;
    if (this.count <= 0) {
      this.end();
    }
  }
}

function HttpRequest(isShowLoading, url, sessionChoose, params, method, callBack, reject) {
  let token = wx.getStorageSync("token");
  let envConfig = wx.getStorageSync('envConfig');

  //判断token是否存在
  // 存在就继续执行
  let header = {
    'content-type': sessionChoose == 1 ? 'application/json' : 'application/x-www-form-urlencoded',
    'X-FROM': 'livePullWxApp',
    'Authorization': 'Bearer ' + token
  }
  url = /^http/.test(url) ? url : (envConfig.apiUrl + url)
  params = Object.prototype.toString.call(params) == "[object Object]" ? params : {};
  params.fromApp = 'xcxlive';

  if (isShowLoading == true) {
    Loading.show();
  }
  wx.request({
    url: url,
    data: params,
    dataType: "json",
    header: header,
    method: method,
    success: function (res) {
      //token 存在 还返回1002，这个时候就要强制
      if (res.data.statusCode == 200) {
        callBack(res.data.data);
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: "none"
        });
      }
    },
    fail: function (res) {
      console.warn("HttpRequst当中wx.request fail 执行了：调用失败", res)
    },
    complete: function (res) {
      console.log(`请求 ${url} 发送的数据是：`, params, '返回的数据是:', res.data.data);
      if (isShowLoading) {
        Loading.hide();
      }
    }
  })

}

function get(url, datas = {}, isShowLoading = true) {
  return new Promise(function (resolve, reject) {
    HttpRequest(isShowLoading, url, 1, datas, 'GET', resolve, reject)
  })
}

function post(url, datas = {}, isShowLoading = true) {
  return new Promise(function (resolve, reject) {
    HttpRequest(isShowLoading, url, 1, datas, 'POST', resolve, reject)
  })
}



function asyncLogin() {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        if (res.code) {
          let envConfig = wx.getStorageSync('envConfig');
          wx.request({
            url: envConfig.apiUrl + 'liveApplet/authByCode',
            data: {
              code: res.code
            },
            dataType: "json",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            method: "POST",
            success: function (res) {
              console.log("wx.login-token:", res)
              if (res.data.data.openId) {
                wx.setStorageSync("userSecret", {
                  openId: res.data.data.openId,
                  sessionKey: res.data.data.sessionKey,
                  unionId: res.data.data.unionId
                });
                resolve(res.data.data)
              }
            },
            fail: function (res) {
              console.warn("wxLogin当中wx.request fail 执行了：调用失败")
              reject();
            }
          })
        } else {
          console.warn('登录失败！' + res.errMsg)
        }
      },
      fail: function () {
        console.warn("调用wx.login接口失败！")
      }
    })
  })
}




// function asyncLogin(flag) {
//   return new Promise((reslove, reject) => {
//     if (login_runing) {
//       //已经在执行了
//       login_collect.push(reslove);
//     } else {
//       login_runing = true;
//       work(reslove, reject, flag)
//     }
//   })
// }


function _resloveRun() {
  login_collect.forEach((reslove) => {
    reslove();
  });
  login_runing = false;
  login_collect = [];
}


function work(reslove, reject, flag) {
  wx.checkSession({
    success: function () {
      //同步获取token
      let token = wx.getStorageSync("token");
      console.log("checkSession是否过期，token:" + token)
      //为了安全验证 判断token是否有本地存储
      if (!token || (!!token && flag)) {
        wxLogin(reslove, reject);
      } else {
        //重新走登录流程
        reslove(token);
        _resloveRun();
      }
    },
    fail: function () {
      //重新走登录流程
      wxLogin(reslove);
    }
  })
}

function wxLogin(resolve, reject) {
  wx.login({
    success(res) {
      console.log("执行了wx.login-code:" + res.code)
      if (res.code) {
        let envConfig = wx.getStorageSync('envConfig');
        wx.request({
          url: envConfig.apiUrl + 'liveApplet/authByCode',
          data: {
            code: res.code
          },
          dataType: "json",
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: "POST",
          success: function (res) {
            console.log("wx.login-token:", res)
            if (res.data.statusCode == 200) {
              if (res.data.data.loginToken) {
                wx.setStorageSync('token', res.data.data.loginToken);
                resolve({
                  token: res.data.data.token
                })
              } else if (res.data.data.openId) {
                wx.setStorageSync("userSecret", {
                  openId: res.data.data.openId,
                  sessionKey: res.data.data.sessionKey,
                  unionId: res.data.data.unionId
                });
                resolve(res.data.data)

              }
            }
          },
          fail: function (res) {
            console.warn("wxLogin当中wx.request fail 执行了：调用失败")
            reject();
          }
        })
      } else {
        console.warn('登录失败！' + res.errMsg)
      }
    },
    fail: function () {
      console.warn("调用wx.login接口失败！")
    }
  })
}



export {
  HttpRequest,
  get,
  post,
  asyncLogin
}